﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq;

namespace ApiManage.Svc.Filter
{
    /// <summary>
    /// 为swagger需登录方法添加ticket
    /// </summary>
    public class AddTicketHeaderParameter : IOperationFilter
    {
        /// <summary>
        /// 为swagger需登录方法添加ticket
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null) operation.Parameters = new List<IParameter>();
            if (!(context.ApiDescription.ActionDescriptor is ControllerActionDescriptor descriptor)) return;
            var actionAttributes = descriptor.MethodInfo.GetCustomAttributes(inherit: true);
            var isAnonymous = actionAttributes.Any(a => a is CheckLoginAttribute);                 //需登录访问的方法,链接中添加值                
            if (isAnonymous)
            {
                operation.Parameters.Add(new NonBodyParameter()
                {
                    Name = "Cookie",
                    In = "header",
                    Type = "string",
                    Required = true,
                    Description = "登录票据"
                });
            }
        }
    }
}
